<template>
  <div>
    <el-dialog
      :model-value="visible"
      class="requirement-task-split-dialog"
      width="800px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      @close="handleClose"
    >
      <template #header>
        <div class="dialog-header">
          <div class="header-title">
            <h3>任务拆分</h3>
            <p v-if="requirement?.title" class="header-subtitle">
              需求：{{ requirement.title }}
            </p>
          </div>
          <VersionStatusTag
            v-if="requirement"
            size="small"
            :status="requirement.status || ''"
          />
        </div>
      </template>

      <div class="dialog-content" v-loading="loading">
        <section class="section requirement-info" v-if="requirementDetail">
          <div class="info-row">
            <span class="info-label">所属项目</span>
            <span class="info-value">{{ requirementDetail.project_name || '—' }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">优先级</span>
            <span class="info-value">{{ requirementDetail.priority || '—' }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">负责人</span>
            <span class="info-value">
              <UserDisplay
                :user-id="requirementDetail.assignee_id"
                :user-name="requirementDetail.assignee_name"
                :show-avatar="false"
                size="small"
              />
            </span>
          </div>
        </section>

        <section class="section">
          <div class="section-title with-action">
            <h4>已有任务（{{ existingTasks.length }}）</h4>
            <el-button 
              type="primary" 
              size="small"
              @click="handleOpenCreateDialog"
            >
              <el-icon><Plus /></el-icon>
              新建任务
            </el-button>
          </div>
          <el-empty
            v-if="!existingTasks.length"
            description="该需求暂无关联任务，点击上方按钮创建任务"
            :image-size="100"
          />
          <el-table
            v-else
            :data="existingTasks"
            size="small"
            border
            height="300"
          >
            <el-table-column prop="title" label="任务标题" min-width="200" show-overflow-tooltip />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <div class="status-cell">
                  <span class="status-dot" :style="{ backgroundColor: getTaskStateColor(row.status) }" />
                  <span>{{ getTaskStateName(row.status) }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="priority" label="优先级" width="90" />
            <el-table-column label="负责人" width="150" show-overflow-tooltip>
              <template #default="{ row }">
                <UserDisplay
                  :user-id="row.assignee_id"
                  :user-name="row.assignee_name"
                  :show-avatar="true"
                  size="small"
                />
              </template>
            </el-table-column>
            <el-table-column prop="due_date" label="截止日期" width="110">
              <template #default="{ row }">
                {{ formatDate(row.due_date, 'YYYY-MM-DD') || '—' }}
              </template>
            </el-table-column>
          </el-table>
        </section>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">关闭</el-button>
          <el-button
            type="primary"
            @click="handleOpenCreateDialog"
          >
            <el-icon><Plus /></el-icon>
            新建任务
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 任务创建对话框 -->
    <TaskCreateDialog
      v-model="createDialogVisible"
      :project-id="requirementDetail?.project_id || ''"
      :default-requirement-id="requirement?.id || ''"
      :default-version-ids="versionId ? [versionId] : []"
      @success="handleTaskCreated"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import type { PropType } from 'vue'
import { ElMessage } from 'element-plus'
import VersionStatusTag from '@/components/version/VersionStatusTag.vue'
import { requirementAPI } from '@/api/requirements'
import { getTaskList } from '@/api/task'
import type { Task } from '@/api/task'
import type { VersionWorkItemNode } from '@/api/version'
import { formatDate } from '@/utils/date'
import { useTaskStates } from '@/composables/useTaskStates'
import type { RequirementResponse } from '@/types/requirement'
import TaskCreateDialog from '@/components/task/TaskCreateDialog.vue'
import { Plus } from '@element-plus/icons-vue'
import UserDisplay from '@/components/ui/UserDisplay.vue'

interface Emits {
  (e: 'update:visible', value: boolean): void
  (e: 'success'): void
}

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  requirement: {
    type: Object as PropType<VersionWorkItemNode | null>,
    default: null
  },
  versionId: {
    type: String,
    default: ''
  }
})

const emit = defineEmits<Emits>()

const loading = ref(false)
const requirementDetail = ref<RequirementResponse | null>(null)
const existingTasks = ref<Task[]>([])
const createDialogVisible = ref(false)

const { loadStates: loadTaskStates, getStateName: getTaskStateName, getStateColor: getTaskStateColor } = useTaskStates()

function handleClose() {
  emit('update:visible', false)
  resetDialog()
}

function resetDialog() {
  requirementDetail.value = null
  existingTasks.value = []
  loading.value = false
  createDialogVisible.value = false
}

async function loadRequirementData() {
  if (!props.visible || !props.requirement?.id) return
  loading.value = true
  try {
    await loadTaskStates()
    requirementDetail.value = await requirementAPI.getRequirementById(props.requirement.id)
    const taskResponse = await getTaskList({
      requirement_id: props.requirement.id,
      size: 100
    })
    existingTasks.value = taskResponse.items || []
  } catch (error) {
    console.error('加载需求或任务数据失败:', error)
    ElMessage.error('加载需求数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

function handleOpenCreateDialog() {
  createDialogVisible.value = true
}

function handleTaskCreated() {
  // 重新加载任务列表
  loadRequirementData()
  emit('success')
}

watch(
  () => props.visible,
  (visible) => {
    if (visible) {
      loadRequirementData()
    } else {
      resetDialog()
    }
  }
)

watch(
  () => props.requirement?.id,
  (newId, oldId) => {
    if (props.visible && newId && newId !== oldId) {
      loadRequirementData()
    }
  }
)
</script>

<style scoped>
.requirement-task-split-dialog .dialog-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  gap: 12px;
}

.header-title h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #1f2d3d;
}

.header-subtitle {
  margin: 4px 0 0;
  font-size: 13px;
  color: #606266;
}

.dialog-content {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.section {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 6px;
  margin: 0;
  font-size: 14px;
  font-weight: 600;
  color: #1f2d3d;
}

.section-title.with-action {
  justify-content: space-between;
}

.requirement-info {
  padding: 12px;
  border-radius: 8px;
  background-color: #f5f7fa;
  gap: 8px;
}

.info-row {
  display: flex;
  justify-content: space-between;
  font-size: 13px;
  color: #606266;
}

.info-label {
  color: #909399;
}

.status-cell {
  display: flex;
  align-items: center;
  gap: 6px;
}

.status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #909399;
}

.task-config {
  display: flex;
  flex-direction: column;
  gap: 12px;
  padding: 12px;
  border-radius: 6px;
  background-color: #fafafa;
}

.config-item {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.config-label {
  font-size: 13px;
  color: #606266;
  font-weight: 500;
}

.task-hint {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 12px;
  color: #909399;
}

.dialog-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.footer-info {
  font-size: 13px;
  color: #606266;
}

.footer-actions {
  display: flex;
  gap: 12px;
}
</style>

